// Expand/collapse the deleted items section
function toggledel() {
	var 
  	expand=document.getElementById('rp_expand'),
  	collapse=document.getElementById('rp_collapse'),
  	area=document.getElementById('rp_deleted');
  
  if(area.style.display=="block") {
    area.style.display="none";
    collapse.style.display="none";
    expand.style.display="inline";
  } else {
    area.style.display="block";
    collapse.style.display="inline";
    expand.style.display="none";
  }
}

// Link/button: Item add
function additem(type) {
  document.getElementById('rp_itemtype').value=type;
  document.getElementById('rp_addform').submit();
}

// Link/button: Extension add
function addextension(extension) {
  document.getElementById('rp_extension').value=extension;
  document.getElementById('rp_addextform').submit();
}

// Button: Deleted filename
function deletefile(name) {
  document.getElementById('rp_deletefile').value=name;
  document.getElementById('rp_edititemform').submit();
}

// Button: cancel editing
function canceledit() {
  if (location.href.indexOf('creating=1') == -1) {
    location.href=location.href.replace(/&item=.*/,'');
  } else {
    document.getElementById('rp_edititemform').action = 'containeritem.php';
    document.getElementById('rp_edititemform').submit();
  }
}


// Button: shared section add
function addshared(type) {  // type currently not used
    document.getElementById('rp_addsharedform').submit();
}


// Drag and drop
////////////////

// Convert event object so it works with both browsers
function fixEvent(e)
{
  if(!e) e=window.event;
  
  if(e.pageX)
    e.mPageX=e.pageX;
  else if(document.body.scrollLeft)
    e.mPageX=e.clientX+document.body.scrollLeft;
  else
    e.mPageX=e.clientX+document.documentElement.scrollLeft;
  if(e.pageY)
    e.mPageY=e.pageY;
  else if(document.body.scrollTop)
    e.mPageY=e.clientY+document.body.scrollTop;
  else
    e.mPageY=e.clientY+document.documentElement.scrollTop;
  if(e.target)
    e.mTarget=e.target;
  else if(e.srcElement)
    e.mTarget=e.srcElement;
  if(e.keyCode) 
  	e.mKey=e.keyCode;
  else if(e.which) 
    e.mKey=e.which;
  
  return e;  
}

// Adds pageX and pageY to the element
function resolvePageXY(e)
{
  e.pageX=e.offsetLeft;  
  e.pageY=e.offsetTop;
  
  var parent=e.offsetParent;
  while(parent!=null)
  {
    e.pageX+=parent.offsetLeft;
    e.pageY+=parent.offsetTop;
    parent=parent.offsetParent;
  }  
  
  e.pageX2=e.pageX+e.offsetWidth;
  e.pageY2=e.pageY+e.offsetHeight;
}

// Drop vertical areas
var targets=new Array();

function inittarget(target) {
  var idsplit=target.id.split('_');
  target.rp_container=idsplit[2];
  target.rp_index=idsplit[3];
  target.rp_parentcontainer=idsplit[4];  
	targets.push(target);
}

function inithandle(handle) {
  var idsplit=handle.id.split('_');
  handle.rp_container=idsplit[2];
  handle.rp_itemid=idsplit[3];
  handle.rp_item=handle.parentNode.parentNode;

  var img=handle.firstChild;
  
  handle.onmousedown=function(e) {
    mousedownHandle(handle,e);
  } 
}

var dragHandle,scrollTimer,shouldScroll;

function mousedownHandle(handle,e) {

  document.onmouseup=mouseupHandle;
  document.onmousemove=mousemoveHandle;
  
  document.getElementById('sourcecontainer').value=handle.rp_container;
  document.getElementById('sourceitem').value=handle.rp_itemid;
  
  dragHandle=handle;
  dragHandle.rp_item.firstChild.nextSibling.style.background="#ccc";    
  
  if(!scrollTimer) {
    shouldScroll=0;
	  scrollTimer=window.setInterval("considerScroll()",100);
  }
  
  var pagemove=document.getElementById('rp_pagemove');
  pagemove.style.display='block';
  pagemove.style.position='absolute'; // It is already, but
  
  var itemPos=pagePos(dragHandle.rp_item);
  var leftPos=itemPos.left-150;
  // Crunch up a bit if there isn't room
  if(leftPos<0) {
  	leftPos=itemPos.left-112; 
  	if(leftPos>0) {
  		leftPos=0;
  	}
  }
  pagemove.style.left=leftPos+'px';
  pagemove.style.top=itemPos.top+"px";
  
  mousemoveHandle(e);
}

function pagePos(item) {
  var result;
  if(item.offsetParent) {
    result=pagePos(item.offsetParent);
  } else {
    result=new Object;
    result.top=0; 
    result.left=0;
  }
  result.top+=item.offsetTop;
  result.left+=item.offsetLeft;
  return result;
}

function considerScroll() {
	if(shouldScroll == 0) { 
		return;
	}
	var scrollPos=getScrollPos();	
	var newPos=scrollPos+shouldScroll;
	if(newPos<0) newPos=0;
	if(newPos!=scrollPos) {
		window.scrollTo(0,newPos);
	}
}

function mouseupHandle(e) {
  e=fixEvent(e);
  document.onmouseup=null;
  document.onmousemove=null;
  
  if(scrollTimer) {
    window.clearInterval(scrollTimer);
  	scrollTimer=null;
  }
  var pagemove=document.getElementById('rp_pagemove');
  pagemove.style.display='none';
  
  if(selectedPage) {
	  document.getElementById('destcontainer').value=selectedPage;    	
	  document.getElementById('moveform').submit();
	} else if(dragHandle.rp_itemid!='c'+document.getElementById('destcontainer').value &&
	          (dragHandle.rp_container!=document.getElementById('destcontainer').value ||
	           dragHandle.rp_firstIndex!=document.getElementById('destindex').value)) {
	  document.getElementById('moveform').submit();
  } else {
	  dragHandle.rp_item.firstChild.nextSibling.style.background='none';  
   	dragHandle=null;
  }
}

function getWindowHeight() {
	if (self.innerHeight) {
		return self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) {
		return document.documentElement.clientHeight; // IE6 strict
	}	else { // other IE
	  return document.body.clientHeight;
	}
}

function getWindowWidth() {
	if (self.innerWidth) {
		return self.innerWidth;
	} else if (document.documentElement && document.documentElement.clientWidth) {
		return document.documentElement.clientWidth; // IE6 strict
	}	else { // other IE
	  return document.body.clientWidth;
	}
}


function mousemoveHandle(e) {
  e=fixEvent(e);
  // If you go out of window then come back, cancel (only works in IE)
  if(document.all && e.button==0)
    return mouseupHandle(e);    
    
  if(!dragHandle) return;
  
  // Check Y against scrolling positions
  var maxY=getWindowHeight()-50;
  if(e.clientY < 50) {
	  shouldScroll=e.clientY-50;
	} else if(e.clientY > maxY) {
	  shouldScroll=e.clientY-maxY; 
	} else {
	  shouldScroll=0;
	}  
  
  // Compare Y against all the targets
  var closest=-1,mindist=0;
  for(var i=0;i<targets.length;i++) {
  	resolvePageXY(targets[i]);
  	if(targets[i].pageY==0 || targets[i].offsetWidth==0) {
  	  continue; // Hidden, i.e. in deleted section
  	}
  	if('c'+targets[i].rp_container == dragHandle.rp_itemid ||
  	   'c'+targets[i].rp_parentcontainer == dragHandle.rp_itemid ) {
  		continue; // Don't let containers be dragged into themselves or their children
  	}
  	var dist=Math.abs(e.mPageY - targets[i].pageY);
  	if(closest==-1 || dist < mindist) {
  	  closest=i;
  	  mindist=dist;
  	}
  }
  var found=targets[closest];
  
  // Move item into specified target
  if(dragHandle.rp_item.parentNode==found) return;
  
  dragHandle.rp_item.parentNode.removeChild(dragHandle.rp_item);
  found.appendChild(dragHandle.rp_item);
  
  document.getElementById('destcontainer').value=found.rp_container;
  
  // Destination sequence is the target index value IF target is before
  // source, otherwise it's that -1.
  var after=false;
  for(var i=0;i<=closest-1;i++) {
    if(targets[i] == dragHandle.rp_lastTarget) 
    {
      after=true;
    }
  }
  var index=found.rp_index - (after && (dragHandle.rp_container == found.rp_container) ? 1 : 0);
  document.getElementById('destindex').value=index;
  
  if(!dragHandle.rp_firstIndex) {
    dragHandle.rp_firstIndex=index;
  }
}

function getScrollPos() {
  // Get scroll position
  if( window.pageYOffset!=undefined) {
    return window.pageYOffset;
  } else if( document.documentElement && document.documentElement.scrollTop!=undefined ) {
    return document.documentElement.scrollTop;
  } else if( document.body && document.body.scrollTop!=undefined ) {
    return document.body.scrollTop;
  }
}

var lastScrollPos;
function updateScrollPos() {
	scrollPos=getScrollPos();
  if(lastScrollPos==scrollPos) {
  	return;
  }
  lastScrollPos=scrollPos;

  // Set in all named inputs and marked links
  var inputs=document.getElementsByTagName('input');
  for(var i=0;i<inputs.length;i++) {
    if(inputs[i].name=='scrollpos') {
      inputs[i].value=scrollPos;
    }
  }
  var links=document.getElementsByTagName('a');
  for(var i=0;i<links.length;i++) {
    if(links[i].className=='scrollpos') {
      var removed=links[i].href.replace(/[?&]scrollpos=[0-9]+/,'');
      if(removed.indexOf('?')==-1) {
        links[i].href=removed+'?scrollpos='+scrollPos;
      } else {
        links[i].href=removed+'&scrollpos='+scrollPos;
      }
    }
  }
}

var selectedPage=null;

// function half-inched from http://www.jeria.net/?p=7
function getCSSProperty(oNode, sProperty)
{
  if(document.defaultView)
  {
    return document.defaultView.getComputedStyle(oNode, null).getPropertyValue(sProperty);
  }
  else if(oNode.currentStyle)
  {
    for(var reExp = /-([a-z])/; reExp.test(sProperty); sProperty = sProperty.replace(reExp, RegExp.$1.toUpperCase()));
	
    return oNode.currentStyle[sProperty];
  }
  else return null;
}
// end half-inching

function selectOtherPage(div) {
  selectedPage=div.id;
  var oldBG=getCSSProperty(div,'background-color');
  div.style.backgroundColor=getCSSProperty(div,'color');
  div.style.color=oldBG;
}

function unselectOtherPage(div) {
  if(selectedPage==div.id) {
  	selectedPage=null;
  }
  var oldBG=getCSSProperty(div,'background-color');
  div.style.backgroundColor=getCSSProperty(div,'color');
  div.style.color=oldBG;
}

function rp_init() {
  var divs=document.getElementsByTagName('div');
  var lastTarget;
  for(var i=0;i<divs.length;i++) {
    var node=divs[i];
    if(node.className=="rp_dragtarget") {
      inittarget(node);
      lastTarget=node;
    } else if(/^rp_draghandle/.test(node.className)) {
      node.rp_lastTarget=lastTarget;
      inithandle(node);
    }
  }
  
  // Scroll to scrollpos, if provided
  var scrollpos=/[?&]scrollpos=([0-9]+)(&.*)?$/;
  var match=scrollpos.exec(window.location.href);
  if(match) {
  	window.scrollTo(0,match[1]);
  }
  
  if(navigator.userAgent.indexOf(' Gecko/')!=-1) {
    // Work around bugzilla.mozilla.org bug 309996
    setInterval(updateScrollPos,250);
  } else {
    window.onscroll=updateScrollPos;
  }
  
  // Hack it so the 'move to page' thing fits on 800x600
  var windowWidth=getWindowWidth();
  if(windowWidth<=915)
  {
    var divs=document.getElementById('content').childNodes;
    for(var i=0;i<divs.length;i++)
    {
      if(divs[i].className && divs[i].className.indexOf('rp_editon')!=-1) 
      {
        divs[i].style.marginRight=(windowWidth<800 ? '0' : windowWidth-800)+'px';
        divs[i].style.width='625px';
      }
    }
  }
}

// function to create a csv ist of items to be placed into another element value
// php code to call this function is display_header in resourcepage_item.php

function checkBoxes(cbox, idprefix, helement) {


    var elementnames = document.getElementsByTagName('input');

    j = 0;

    idlist = '';

    for(i=0; i < elementnames.length; i++) {


	if(elementnames[i].type == "checkbox" && elementnames[i].id.substring(0, idprefix.length) == idprefix  && elementnames[i].checked) {


		// add to list

	    	idlist = idlist + elementnames[i].value + ',';


         } // endif	


    } // endfor


    helement.value = idlist;



} 

// container edit functions

// Button: cancel editing
function cancelcontaineredit() {
  if (location.href.indexOf('creating=1') == -1) {
    location.href=location.href.replace(/&item=.*/,'');
  } else {
    document.getElementById('rp_editcontainerform').action = 'containeritem.php';
    document.getElementById('rp_editcontainerform').submit();
  }
}

//Reference export functions

//(de)select all ref item checkboxes
function rp_selRefs(allnone){
	var elementnames = document.getElementsByTagName('input');
	var idprefix="refmultiselect_";
	for(i=0;i<elementnames.length;i++){
		if(elementnames[i].type == "checkbox" && elementnames[i].id.substring(0, idprefix.length) == idprefix){
			if(allnone){
				elementnames[i].checked=true;
			}else{
				elementnames[i].checked=false;
			}
		}
	}
}

//submit ref export - get all check items and put into hidden form field
function rp_exportRefs(){
	checkBoxes('',"refmultiselect_",document.getElementById("multi_idlist"));
	return true;
}

